import json
from collections import defaultdict

from odoo.http import request, Response
from odoo import http, _


class WorkCenterApi(http.Controller):
    @http.route("/api/work_center", auth='user', type='json', methods=['POST'], csrf=True)
    def create_workcenter(self, **kwargs):
        """
        工作中心创建
        """
        data = request.params
        name = data.get('name')  # 工作中心（名称）
        code = data.get('code')  # 工作中心（编码）
        if not code or not name:
            return {'code': 0, 'msg': _('code or name is required')}
        # 检查工作中心是否已存在
        work_name = request.env['mrp.workcenter'].search([('code', '=', code)], limit=1)
        if work_name:
            return {'code': 0, 'msg': _('%s Already exists, please re-enter') % name}
        # 工站代码
        work_station_code = data.get('work_station_code')
        # 泰文
        thai_name = data.get('thai_name')
        # 英文
        eng_name = data.get('eng_name')
        # 计数点
        is_enter_bcode = data.get('is_enter_bcode')
        # 日期代码点
        is_date_code = data.get('is_date_code')
        # 工序参数
        param_line_data = data.get('param_line_data') or []
        result = self.get_param_line_ids(param_line_data, create=True)
        if result.get('code') != 200:
            return result
        param_line = result.get('data')
        # 查找工作站
        station = request.env['work.station'].search([('code', '=', work_station_code)], limit=1)
        # 如果工作站不存在, 返回创建失败
        if not station:
            return {'code': 0, 'msg': _('Work station %s does not exist') % work_station_code}
        workcenter_data = {
            'name': name,
            'work_station_id': station.id,
            'thai_name': thai_name,
            'eng_name': eng_name,
            'code': code,
            'resource_calendar_id': request.env.company.resource_calendar_id.id,
            'is_enter_bcode': is_enter_bcode,
            'is_date_code': is_date_code,
            'param_line_ids': param_line,
        }
        workcenter = request.env['mrp.workcenter'].create(workcenter_data)
        data = {
            "workcenter_id": workcenter.id,
            "param_lines_created": len(param_line_data),
            'name': workcenter.name,
            'code': workcenter.code,
        }
        return {'code': 200, 'msg': 'success', 'data': data}

    @http.route("/api/work_center", auth='user', type='json', methods=['PUT'], csrf=True)
    def update_workcenter(self, **kwargs):
        data = request.params
        workcenter_code = data.get('code')
        workcenter = request.env['mrp.workcenter'].search([('code', '=', workcenter_code)], limit=1)
        if not workcenter:
            return {'code': 0, 'msg': _('Work center %s does not exist') % workcenter_code}
        # 逻辑判断
        name = data.get('name')
        code = data.get('code')
        if not code or not name:
            return {'code': 0, 'msg': 'code or name is required'}
        # 更新字段，直接覆盖
        try:
            # 查找或创建工作站
            station = request.env['work.station'].search([('code', '=', data.get('work_station_code'))], limit=1)
            if not station:
                return {'code': 0, 'msg': _('Work station %s does not exist') % data.get('work_station_code')}
            # 处理参数行数据
            param_line_data = data.get('param_line_data') or []
            result = self.get_param_line_ids(param_line_data, create=False)
            if result.get('code') != 200:
                return result
            param_line = result.get('data')
            # 删除原有的, 使用新增
            workcenter.param_line_ids.unlink()
            workcenter.write({
                'name': name,
                'code': code,
                'work_station_id': station.id,
                'thai_name': data.get('thai_name'),
                'eng_name': data.get('eng_name'),
                # 'is_enter_bcode': data.get('is_enter_bcode'),
                # 'is_date_code': data.get('is_date_code'),
                'param_line_ids': param_line
            })
            return {'code': 200, 'msg': 'success'}
        except Exception as e:
            return {'code': 0, 'msg': str(e)}

    @classmethod
    def get_param_line_ids(cls, param_line_data, create):
        param_line = []
        index = 1
        for record in param_line_data:
            attribute_code = record.get('attribute_code')
            attribute_name = record.get('attribute_name')
            attribute_thai = record.get('attribute_thai')
            attribute_eng = record.get('attribute_eng')
            domain = [('code', '=', attribute_code), ('limit_type', '=', 'route')]
            attribute = request.env['product.attribute'].search(domain, limit=1)
            # 工序不存在, 且为修改不允许创建
            # if not attribute and not create:
            #     return {'code': 0, 'msg': 'Process parameter %s does not exist' % attribute_code}
            # 工序参数不存在
            if not attribute:
                attribute = request.env['product.attribute'].create({
                    'code': attribute_code,
                    'name': attribute_name,
                    'thai_name': attribute_thai,
                    'eng_name': attribute_eng,
                    'limit_type': 'route',
                })
            else:
                # 更新泰文英文
                attribute.write({
                    'name': attribute_name,
                    'thai_name': attribute_thai,
                    'eng_name': attribute_eng,
                })
            value_name = record.get('value_name')
            value_thai = record.get('value_thai')
            value_eng = record.get('value_eng')
            if not value_name:
                param_line.append((0, 0, {
                    'sequence': index,
                    'attribute_id': attribute.id
                }))
                index += 1
                continue
            value = attribute.value_ids.filtered(lambda x: x.name == value_name)
            if len(value) > 1:
                value = value[0]
            if not value:
                value = request.env['product.attribute.value'].create({
                    'name': value_name,
                    "thai_name": value_thai,
                    "eng_name": value_eng,
                    'attribute_id': attribute.id
                })
            else:
                # 更新泰文英文
                value.write({
                    "thai_name": value_thai,
                    "eng_name": value_eng,
                })
            param_line.append((0, 0, {
                'sequence': index,
                'attribute_id': attribute.id,
                'value_id': value.id,
            }))
            index += 1
        return {'code': 200, 'msg': 'success', 'data': param_line}

    @http.route(["/api/work_station"], auth='user', type='http', methods=['GET'], csrf=True)
    def get_work_station(self, **kwargs):
        """
        获取工站
        """
        page = int(kwargs.get('page') or 1)
        page_size = int(kwargs.get('pageSize') or 20)
        domain = []
        name = kwargs.get('name')
        if name:
            domain.append(('name', 'ilike', kwargs['name']))
        code = kwargs.get('code')
        if code:
            domain.append(('code', 'ilike', kwargs['code']))
        else:
            domain.append(('code', '!=', False))
        station_ids = request.env['work.station'].search(domain, offset=(page - 1) * page_size,
                                                         limit=page_size)
        if not station_ids:
            return Response(json.dumps({'code': 0, 'msg': _('Work station does not exist')}),
                            mimetype='application/json', status=404)
        data_list = []
        for station in station_ids:
            data_list.append({
                'name': station.name,
                'code': station.code,
            })
        return Response(json.dumps({'code': 200, 'msg': 'success', 'data': data_list}),
                        mimetype='application/json', status=200)

    @http.route("/api/product/attribute", auth='user', type='http', methods=['GET'], csrf=True)
    def get_product_attribute(self, **kwargs):
        """
        工序参数,规格参数
        """
        page = kwargs.get('page') or 1
        page_size = kwargs.get('pageSize') or 20
        data_list = []
        code = kwargs.get('code')
        if code:  # 支持模糊查询
            domain = [('code', 'ilike', code)]
        else:
            domain = [('code', '!=', False)]
        try:
            attribute_ids = request.env['product.attribute'].search(domain, offset=(int(page) - 1) * int(page_size),
                                                                    limit=int(page_size))
            for attribute in attribute_ids:
                value_list = []
                for value in attribute.value_ids:
                    value_list.append({
                        'name': value.name,
                        'thai_name': value.thai_name or '',
                        'eng_name': value.eng_name or '',
                    })
                data_list.append({
                    'name': attribute.name,
                    'code': attribute.code,
                    'thai_name': attribute.thai_name or '',
                    'eng_name': attribute.eng_name or '',
                    'values': value_list
                })
            return Response(json.dumps(data_list), mimetype='application/json', status=200)
        except Exception as e:
            return Response(json.dumps({'code': 400, 'msg': _('Error fetching product attributes')}),
                            mimetype='application/json', status=400)

    @http.route("/api/work_center", auth='user', type='http', methods=['GET'], csrf=True)
    def detail_workcenter(self, **kwargs):
        """
        获取工作中心详情
        """
        code = kwargs.get('code')
        if not code:
            return http.Response(json.dumps({'code': 0, 'msg': _('code is required')}), mimetype='application/json')
        workcenter = request.env['mrp.workcenter'].search([('code', '=', code)], limit=1)
        if not workcenter:
            return http.Response(json.dumps({'code': 0, 'msg': _('Work center %s does not exist') % code}),
                                 mimetype='application/json')
        param_line_ids = []
        for param in workcenter.param_line_ids:
            param_line_ids.append({
                'id': param.id,
                'attribute_code': param.attribute_id.code,
                'attribute_name': param.attribute_id.name,
                'attribute_thai': param.thai_name or '',
                'attribute_eng': param.eng_name or '',
                'value_name': param.value_id.name or '',
                'value_thai': param.z_thai_name or '',
                'value_eng': param.z_eng_name or '',
            })
        data = {
            'id': workcenter.id,
            'name': workcenter.name,
            'code': workcenter.code,
            'work_station_code': workcenter.work_station_id.code,
            'work_station_name': workcenter.work_station_id.name,
            'thai_name': workcenter.thai_name or '',
            'eng_name': workcenter.eng_name or '',
            'param_line_ids': param_line_ids
        }
        return http.Response(json.dumps({'code': 200, 'msg': 'success', 'data': data}), mimetype='application/json')

    @http.route("/api/attribute/preferential", auth='user', type='json', methods=['POST'], csrf=True, cors='*')
    def preferential(self, **kwargs):
        """工序参数获取"""
        keywords = kwargs.get('keyword') or []
        if not isinstance(keywords, list):
            return {'code': 400, 'msg': _('keyword must be a list')}
        data = []
        domain = [('attribute_id.limit_type', '=', 'route'), ('workcenter_id', '!=', False), ('thai_name', '!=', False)]
        for keyword in keywords:
            domain.append(('attribute_id.name', '=', keyword))
            param = request.env['mrp.workcenter.param.line'].sudo().search(domain)
            if len(param) != 1:
                continue
            data.append({
                'attribute_name': param.attribute_id.name,
                'attribute_thai': param.thai_name,
                'attribute_eng': param.eng_name,
            })
        # dictf = defaultdict(dict)
        # for record in param:
        #     if record.thai_name in dictf[record.attribute_id.name]:
        #         dictf[record.attribute_id.name][record.thai_name].append(record)
        #     else:
        #         dictf[record.attribute_id.name][record.thai_name] = [record]
        # bs = {}
        # for key, value in dictf.items():
        #     for k, v in value.items():
        #         if key in bs:
        #             sk = bs[key]
        #             if sk.get('num') < len(v):  # 替换最新数量
        #                 bs[key] = {
        #                     'num': len(v),
        #                     'thai_name': k,
        #                     'eng_name': v[0].eng_name or '',
        #                 }
        #         else:
        #             bs[key] = {
        #                 'num': len(v),
        #                 'thai_name': k,
        #                 'eng_name': v[0].eng_name or '',
        #             }
        # for rec, vla in bs.items():
        #     data.append({
        #         'attribute_name': rec,
        #         'attribute_thai': vla.get('thai_name'),
        #         'attribute_eng': vla.get('eng_name'),
        #     })
        return data

    @http.route("/api/attribute/lang", auth='user', type='json', methods=['POST'], csrf=True, cors='*')
    def attribute_lang(self, **kwargs):
        attribute = kwargs.get('code') or []
        objs = request.env['product.attribute'].sudo().search([('code', 'in', attribute)])
        data = []
        for record in objs:
            data.append({
                'name': record.name,
                'code': record.code,
                'thai': record.thai_name or '',
                'eng': record.eng_name or '',
            })
        return data

    @http.route("/api/attribute/post", auth='user', type='json', methods=['POST'], csrf=True, cors='*')
    def attribute_post(self, **kwargs):
        """
        批量更新参数

        需要同步操作
        1.工作中心-工序参数
        2.物料清单-工序参数

        一个编码存在多个情况, 如存在多个则同步更新
        """
        data = kwargs.get('data') or []
        for record in data:
            if not record.get('code'):
                return {'code': 400, 'msg': _('code is required')}
            attribute = request.env['product.attribute'].sudo().search([('code', '=', record.get('code'))])
            if not attribute:
                return {'code': 400, 'msg': _('Attribute %s does not exist') % record.get('code')}
            attribute.update({
                'name': record.get('name'),
                'thai_name': record.get('thai'),
                'eng_name': record.get('eng'),
            })
            # 同步操作
            res = request.env['mrp.workcenter.param.line'].sudo().search([('attribute_id', '=', attribute.id)])
            res.update({
                'thai_name': record.get('thai'),
                'eng_name': record.get('eng'),
            })
        return {'code': 200, 'msg': 'success', 'data': ''}

    @http.route("/api/station/lang", auth='user', type='json', methods=['POST'], csrf=True, cors='*')
    def station_lang(self, **kwargs):
        """
        工站及工作中心参数
        """
        codes = kwargs.get('code') or []
        objs = request.env['work.station'].sudo().search([('code', 'in', codes)])
        data = []
        for record in objs:
            worker_center = []
            for rec in record.center_ids:
                worker_center.append({
                    'name': rec.name,
                    'code': rec.code,
                    'thai': rec.thai_name or '',
                    'eng': rec.eng_name or '',
                })
            data.append({
                'name': record.name,
                'code': record.code,
                'thai': record.name_thai or '',
                'eng': record.name_eng or '',
                'center_ids': worker_center,
            })
        return data
